/* 
 * Enterprise Library Extensions - DI + ORM.
 * Copyright (C) 2006
 *
 * GNU General Public License
 *
 * This program is free software; you can redistribute 
 * it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using ELE.EnterpriseLibrary.Data.Configuration;

namespace ELE.EnterpriseLibrary.Data
{
  /// <summary>
  /// Custom factory for <see cref="ObjectSqlQueryManager"/>s.
  /// </summary>
  public class ObjectSqlQueryManagerCustomFactory : ICustomFactory
  {
    /// <summary>
    /// Creates a <see cref="ObjectSqlQueryManager"/> from a configuration source.
    /// </summary>
    /// <param name="context"></param>
    /// <param name="name"></param>
    /// <param name="configurationSource"></param>
    /// <param name="reflectionCache"></param>
    /// <returns></returns>
    public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
    {
      ObjectSqlQueryConfigurationView view = new ObjectSqlQueryConfigurationView(configurationSource);
      ObjectSqlQueryManager createdObject = null;
      SqlQueryData queryData = view.GetSqlQueryData(name);
      if (queryData != null)
      {
        ObjectSqlQuery query = new ObjectSqlQuery(name);
        query.SqlText = queryData.Sql; 
        QueryBuilderData qbData = view.GetQueryBuilderData(queryData.QueryBuilder);
        ISqlQueryBuilder queryBuilder = (ISqlQueryBuilder)Activator.CreateInstance(Type.GetType(qbData.Type));
        query.QueryBuilder = queryBuilder;
        query.Mappings = new List<ObjectSqlMapping>();
        foreach(MappingReferenceData mapRef in queryData.Mappings)
        {
          ObjectSqlMapping map = new ObjectSqlMapping(mapRef.ObjectId, mapRef.Name);
          if (mapRef.OverwriteBindings != null)
          {
            ObjectSqlMappingTable table = new ObjectSqlMappingTable("Overwrites");
            table.IsPrimary = true;
            map.PrimaryTableName = "Overwrites";
            foreach (PropertyBindingOverwriteData owBind in mapRef.OverwriteBindings)
            {
              ObjectPropertySqlBinding binding = new ObjectPropertySqlBinding(owBind.Name);
              binding.Ignore = owBind.Ignore;
              binding.OutputFieldName = owBind.OutName;
              binding.InputFieldName = owBind.InName;
              binding.NullableValue = owBind.NullableValue;
              table.AddBinding(binding);
            }
            map.AddTable(table);
          }
          query.Mappings.Add(map);
        }
        createdObject = new ObjectSqlQueryManager(query);
      }

      RegisterObject(context, name, createdObject);
      return createdObject;
    }
    private void RegisterObject(IBuilderContext context, string name, ObjectSqlQueryManager createdObject)
    {
      if (context.Locator != null)
      {
        ILifetimeContainer lifetime = context.Locator.Get<ILifetimeContainer>(typeof(ILifetimeContainer), SearchMode.Local);

        if (lifetime != null)
        {
          context.Locator.Add(new DependencyResolutionLocatorKey(typeof(ObjectSqlQueryManager), name), createdObject);
          lifetime.Add(createdObject);
        }
      }
    }
  }

}
